package cn.wei.youvie.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.wei.youvie.common.constant.CommonConstant;
import cn.wei.youvie.common.exception.BusinessException;
import cn.wei.youvie.common.exception.ThrowUtils;
import cn.wei.youvie.common.servlet.DeleteRequest;
import cn.wei.youvie.common.servlet.ErrorCode;
import cn.wei.youvie.domain.dto.chapter.ChapterAddRequest;
import cn.wei.youvie.domain.dto.chapter.ChapterQueryRequest;
import cn.wei.youvie.domain.dto.chapter.ChapterUpdateRequest;
import cn.wei.youvie.domain.entity.Book;
import cn.wei.youvie.domain.entity.Chapter;
import cn.wei.youvie.domain.entity.User;
import cn.wei.youvie.domain.vo.ChapterVO;
import cn.wei.youvie.domain.vo.SectionVO;
import cn.wei.youvie.service.BookService;
import cn.wei.youvie.service.UserService;
import cn.wei.youvie.utils.SqlUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.wei.youvie.service.ChapterService;
import cn.wei.youvie.mapper.ChaptersMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Youvie
* @description 针对表【chapters(存储书籍中的章节信息)】的数据库操作Service实现
* @createDate 2024-08-27 21:02:10
*/
@Service
public class ChapterServiceImpl extends ServiceImpl<ChaptersMapper, Chapter>
    implements ChapterService {

    @Autowired
    private UserService userService;

    @Autowired
    @Lazy
    private BookService bookService;

    @Autowired
    private ChaptersMapper chaptersMapper;

    @Override
    public Integer add(ChapterAddRequest chapterAddRequest, HttpServletRequest request) {
        if (chapterAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        if (isAuthChapterUpdate(request, chapterAddRequest.getBookId())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "只有书本创建人或者管理员可以添加对应的书本章节");
        }

        Chapter chapter = new Chapter();
        BeanUtils.copyProperties(chapterAddRequest, chapter);

        boolean saved = this.save(chapter);
        ThrowUtils.throwIf(!saved, ErrorCode.OPERATION_ERROR);
        return chapter.getChapterId();
    }

    @Override
    public boolean deleteChapter(DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        long id = deleteRequest.getId();
        // 判断是否存在
        Chapter oldChapter = this.getById(id);
        ThrowUtils.throwIf(oldChapter == null, ErrorCode.NOT_FOUND_ERROR);

        // 仅书本创建人或管理员可删除
        isAuthChapterUpdate(request, oldChapter.getBookId());

        return this.removeById(id);
    }

    /**
     * 判断当前人是否可以修改或者添加章节
     */
    private boolean isAuthChapterUpdate(HttpServletRequest request, int bookId) {
        User user = userService.getLoginUser(request);

        Book book = bookService.getById(bookId);

        return !book.getUserId().equals(user.getId()) && !userService.isAdmin(request);
    }

    @Override
    public boolean updateChapter(ChapterUpdateRequest chapterUpdateRequest) {
        Chapter chapter = new Chapter();
        BeanUtils.copyProperties(chapterUpdateRequest, chapter);
        long id = chapterUpdateRequest.getBookId();
        // 判断是否存在
        Chapter oldChapter = this.getById(id);
        ThrowUtils.throwIf(oldChapter == null, ErrorCode.NOT_FOUND_ERROR);

        return this.updateById(chapter);
    }

    @Override
    public ChapterVO getChapterVO(Chapter chapter, HttpServletRequest request) {
        ChapterVO chapterVO = new ChapterVO();
        BeanUtils.copyProperties(chapter, chapterVO);
        return chapterVO;
    }

    @Override
    public Wrapper<Chapter> getQueryWrapper(ChapterQueryRequest chapterQueryRequest) {

        String sortField = chapterQueryRequest.getSortField();
        String sortOrder = chapterQueryRequest.getSortOrder();

        QueryWrapper<Chapter> chapterQueryWrapper = new QueryWrapper<>();
        if (chapterQueryRequest.getBookId() != null) {
            chapterQueryWrapper.eq("book_id", chapterQueryRequest.getBookId());
        }
        chapterQueryWrapper.like(chapterQueryRequest.getTitle() != null, "title", chapterQueryRequest.getTitle());
        chapterQueryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return chapterQueryWrapper;
    }

    @Override
    public Page<ChapterVO> getChapterVOPage(Page<Chapter> chapterPage, HttpServletRequest request) {
        List<Chapter> chapterList = chapterPage.getRecords();
        Page<ChapterVO> chapterVOPage = new Page<>(chapterPage.getCurrent(), chapterPage.getSize(), chapterPage.getTotal());
        if (CollUtil.isEmpty(chapterList)) {
            return chapterVOPage;
        }

        // 填充信息
        List<ChapterVO> chapterVOList = chapterList.stream()
                .map(ChapterVO::objToVo)
                .collect(Collectors.toList());

        chapterVOPage.setRecords(chapterVOList);
        return chapterVOPage;
    }

    @Override
    public ChapterVO getContentsByChapterId(ChapterQueryRequest chapterQueryRequest, HttpServletRequest request) {
        List<SectionVO> contents = chaptersMapper.getContentsByChapterId(chapterQueryRequest.getChapterId());

        ChapterVO chapterVO = new ChapterVO();
        chapterVO.setSections(contents);
        return chapterVO;
    }
}




